package com.zjmzxfzhl.integrityconstraint.service.impl;

import com.zjmzxfzhl.integrityconstraint.config.IntegrityConstraintProperties;
import com.zjmzxfzhl.integrityconstraint.pojo.ToCheck;
import com.zjmzxfzhl.integrityconstraint.service.AbstractIntegrityConstraintService;
import com.zjmzxfzhl.integrityconstraint.entity.IntegrityConstraint;
import com.zjmzxfzhl.integrityconstraint.entity.IntegrityConstraintRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * jdbc方式实现的业务完整性验证实现类
 *
 * @author 庄金明
 */
public class JdbcIntegrityConstraintService extends AbstractIntegrityConstraintService {
    private final JdbcTemplate jdbcTemplate;

    public JdbcIntegrityConstraintService(JdbcTemplate jdbcTemplate, IntegrityConstraintProperties integrityConstraintProperties) {
        super(integrityConstraintProperties);
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Boolean save(IntegrityConstraint integrityConstraint) {
        String sqlDelete = "delete from integrity_constraint t where t.business_key=? and t.verify_type=?";
        jdbcTemplate.update(sqlDelete, integrityConstraint.getBusinessKey(), integrityConstraint.getVerifyType());
        String sql = "insert into integrity_constraint(business_key,verify_type,json_data,create_time,expire) values (?,?,?,?,?)";
        int result = jdbcTemplate.update(sql, integrityConstraint.getBusinessKey(), integrityConstraint.getVerifyType(), integrityConstraint.getJsonData(), integrityConstraint.getCreateTime(), integrityConstraint.getExpire());
        return result > 0;
    }

    @Override
    public Boolean check(String businessKey, List<ToCheck> toChecks) {
        List<IntegrityConstraint> integrityConstraints = this.getList(businessKey);
        return this.commonCheck(integrityConstraints, toChecks);
    }

    @Override
    public Boolean delete(String businessKey) {
        String sqlDelete = "delete from integrity_constraint t where t.business_key=?";
        int result = jdbcTemplate.update(sqlDelete, businessKey);
        return result > 0;
    }

    protected List<IntegrityConstraint> getList(String businessKey) {
        String sql = "select t.business_key businessKey,t.verify_type verifyType,t.json_data jsonData,t.create_time createTime,t.expire expire from integrity_constraint t where t.business_key=? order by t.create_time";
        List<IntegrityConstraint> integrityConstraints = jdbcTemplate.query(sql, new IntegrityConstraintRowMapper(), businessKey);
        return integrityConstraints;
    }
}
